﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MKAdminCore.Controllers;
using MKAdminCore.DTO.Web.Common;
using MKAdminCore.DTO.Web.Excel.Import;
using MKAdminCore.IService.Web.Excel;
using MKAdminCore.ToolKit.Config;
using MKAdminCore.ToolKit.ExcelHelper;
using MKAdminCore.ToolKit.Extensions;

namespace MKAdminCore.Areas.Excel.Controllers
{
    [Area("Excel")]
    [Route("Excel/[controller]/[action]")]
    public class ImportController : BaseMvcController
    {
        private IImportService _iImportService;

        public ImportController(IImportService iImportService)
        {
            _iImportService = iImportService;
        }

        public IActionResult Index()
        {
            return View(PageViewFilesConfig.ExcelImportIndex);
        }

        /// <summary>
        /// 导入数据
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> ImportData(ImportDataParameter parameter)
        {
            var result = new HttpResponseResult();

            var catalogConfig = AppSettingConfigExtensions.GetUploadFileConfigInfo("Excel");

            string filePath = $@"{catalogConfig.SavePath}/{parameter.catalog.Replace("/", "\\")}\{parameter.fileName}";

            DataTable dtResult = ExcelHelper.ImportToDataTable(new ExcelConvertToDataParamater()
            {
                fileName = filePath
            });
            if (dtResult != null && dtResult.Rows.Count > 0)
            {
                if (dtResult.Columns.Count == 6)
                {
                    var userInfo = base.GetUserInfo();

                    result = await _iImportService.ImportData(dtResult, userInfo);
                }
                else
                {
                    result.Code = (int)HttpResponseCode.BadRequest;
                    result.Msg = "导入文件格式有误!";
                }
            }
            else
            {
                result.Code = (int)HttpResponseCode.BadRequest;
                result.Msg = "导入文件中未检测到数据!";
            }

            return Ok(result);
        }
    }
}